
package com.test.utils;


import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @description 校验工具
 * @author  kang
 */
@FunctionalInterface
public interface ValidatorPredicate {

    String LOG_PARAM_PLACEHOLDER = "\\{\\}";

    Pattern LOG_PARAM_PATTERN = Pattern.compile(LOG_PARAM_PLACEHOLDER);

    Boolean apply(Boolean e);

    default ValidatorPredicate andThen(String msg, Object... params) {
        return e -> {
            Boolean f = this.apply(e);
            if (f){
                String message = logFormat(msg, params);
                throw new RuntimeException(message);
            }
            return true;
        };
    }

    private static String logFormat(String message, Object... arguments) {
        if (arguments != null && arguments.length > 0){
            Matcher m = LOG_PARAM_PATTERN.matcher(message);
            int i = 0;
            while (m.find() && i < arguments.length) {
                message = message.replaceFirst(LOG_PARAM_PLACEHOLDER, String.valueOf(arguments[i++]));
            }
        }
        return message;
    }

    static ValidatorPredicate identity() {
        return t -> t;
    }

}
